//
//  LivingViewController.m
//  LiveStar
//
//  Created by 漪珊 on 2016/12/20.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "LivingViewController.h"
#import "LivingfunctionView.h"
#import "SendRedPaperView.h"
#import <IMSDK/TIMGroupManager.h>
#import <IMSDK/TIMMessage.h>
#import "LSIMPlatform.h"
#import "LSPushMgr.h"
#import "StarPresentView.h"
#import "SPresentListModel.h"
#import "AnimOperationManager.h"

#define kPresentHeight 280

@interface LivingViewController ()<LivingfunctionViewDelegate,TIMUserStatusListener,TXLivePushListener,StarPresentViewDelegate,SendRedPaperDelegate,UITextFieldDelegate>
{
    TXLivePush *_txLivePush; //推流管理
    TIMManager *_timmanager; //IM管理
    TIMGroupManager *_timGroupManager; //群组管理
    TIMConversation *_chatRoomConversation;   // 群会话上下文
    StarPresentView *_starPresentView;//礼品界面
    AVIMMsgHandler *_immsgHandler;
    UIAlertView *_closeErrRstAlert;
    UIAlertView *_closeErrAlert;
    NSString *_roomid;
    NSString *_chatroomid;
    
    NSMutableArray *_SpresentListArr;//礼物列表数组

}
@property (nonatomic, strong) LivingfunctionView *functionView;
@property (nonatomic, strong) SendRedPaperView *paperView;
@property (nonatomic, strong) UIView *videoView;

/**
   记录当前选中的按钮
 */
@property (nonatomic, strong) UIButton *selectedBtn;

/**
   红包 金额 人数 文本框 发送按钮
 */
@property (nonatomic, strong) UITextField *moneyTextField;
@property (nonatomic, strong) UITextField *membersTextField;
@property (nonatomic, strong) UIButton *sendBtn;

@end

@implementation LivingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSLog(@"SDK Version = %@", [[TXLivePush getSDKVersion] componentsJoinedByString:@"."]);
    
    [self setNav];
    
    [self setUpUI];
    
    [self registNotice];
    
    [self setUpLive];
    
    [self registeIM];
    
    [_txLivePush startPreview:self.functionView];
    [self.functionView setMsgHandler:_immsgHandler];
    
    [self sendRtmpURlRequest];
}

#pragma mark -- 注册通知
- (void)registNotice {
    //先注册后退消息通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleEnterBackground:)name:UIApplicationDidEnterBackgroundNotification object:nil];
    //注册进入前台
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleEnterForeground:)name:UIApplicationWillEnterForegroundNotification object:nil];
    //监听TextField的变化
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldChanged:) name:UITextFieldTextDidChangeNotification object:nil];
}

#pragma mark -- 设置应用后台运行
//进入后台
- (void)handleEnterBackground:(NSNotification *)notifica {
    [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
//        [_txLivePush resumePush];
    }];
    if ([_txLivePush isPublishing]) {
        [_txLivePush pausePush];
    }
}

//回到前台
- (void)handleEnterForeground:(NSNotification *)notifica {
    if ([_txLivePush isPublishing]) {
        [_txLivePush resumePush];
    }
}

#pragma mark -- IM

- (void)registeIM {
    LSIMPlatform *lsIMPlatform = [[LSIMPlatform alloc] init];
    [lsIMPlatform initIMSDK];
    [lsIMPlatform loginIMSDKWithIMUserModelWithSucc:^{//登录IM成功后请求直播URL
        
    } Fail:^(int code, NSString *msg) {
        
    }];
}
#pragma mark -- 礼物列表请求
- (void)PresentListRequset {
    NSString *userType = KString([[LSUserInfoManager sharedManager] currentUserInfo].u_type);
    NSDictionary *dict = @{
                           @"udid":User_ID,
                           @"token":TOKEN,
                           @"type":userType
                           };
    NSString *urlString = [TEST_URL stringByAppendingString:kGifList];
    [NetworkTools postReqeustWithParams:dict UrlString:urlString successBlock:^(id responseObject) {
        if ([KString(responseObject[@"code"]) isEqualToString:@"200"] ) {
            if (_SpresentListArr.count > 0) {
                [_SpresentListArr removeAllObjects];
            }
            NSArray *array = responseObject[@"data"][@"list"];
            for (NSDictionary *PresentDic in array) {
                SPresentListModel *prsentModel = [[SPresentListModel alloc] initWithDict:PresentDic];
                [_SpresentListArr addObject:prsentModel];
            }
            if (!_SpresentListArr.count) {
                [self showTitle:@"当前没有礼物可送!"];
            } else {
                for (int i = 0; i < _SpresentListArr.count; i++) {
                    UIButton *btn = _starPresentView.ButtonArray[i];
                    SPresentListModel *prsentModel = _SpresentListArr[i];
                    [btn setTitle:prsentModel.g_name forState:UIControlStateNormal];
                }
                if (_starPresentView) {
                    [self.view addSubview:_starPresentView];
                    [self SelectPresent:_starPresentView.PresentOne];
                }
            }
        }
    } failureBlock:^(NSError *error) {
        
    } showHUD:NO];
}


#pragma mark --  sendRtmpURlRequest
- (void)sendRtmpURlRequest {//请求推流URL
    [[LSPushMgr alloc] getPushUrlWithGroupID:@"1" hander:^(NSError *error, NSString *pushUrl,NSString *roomid, NSString *chatroomid) {
        if (error == nil && pushUrl!=nil) {//获取推流地址成功
            [self startRtmpPushWithPushUrl:pushUrl];
            _roomid = roomid;
            _chatroomid = chatroomid;
            _immsgHandler = [[AVIMMsgHandler alloc] init];
            _immsgHandler.groupId = chatroomid;
            _immsgHandler.chatRoomConversation = [[TIMManager sharedInstance] getConversation:TIM_GROUP receiver:KString(chatroomid)];
            [self.functionView setMsgHandler:_immsgHandler];
        } else {//失败
            [self showTitle:@"直播开始失败,请重新开启..."];
        }
    }];
}


#pragma mark -- 发送礼物Request
- (void)sendPresentRequestWithPresentModel:(SPresentListModel *)model {
    NSDictionary *dict = @{
                           @"udid":User_ID,
                           @"token":TOKEN,
                           @"channel":_roomid,
                           @"group":_chatroomid,
                           @"gid":model.g_id,
                           @"amount":@"1",
                           };
    NSString *urlString = [TEST_URL stringByAppendingString:kStarSendGif];
    [self showHUDInView:self.view title:@"礼物发送中..."];
    [NetworkTools postReqeustWithParams:dict UrlString:urlString successBlock:^(id responseObject) {
        [self hideHUD];
        if ([KString(responseObject[@"code"]) isEqualToString:@"200"]) {
            if (_SpresentListArr) {
                [_SpresentListArr removeAllObjects];
            }
            NSArray *array = responseObject[@"data"][@"gift"];
            NSString *msg = responseObject[@"data"][@"message"];
            UserModel *model = [[LSUserInfoManager sharedManager] currentUserInfo];
            LSMsgModel *msgModel = [[LSMsgModel alloc] init];
            msgModel.userName = model.u_nickname;
            msgModel.userMsg  = msg;
            msgModel.userHeadImageUrl = model.u_avatar;
            msgModel.msgType = TCMsgModelType_NormalMsg;
            
            [_immsgHandler sendMessage:AVIMCMD_Star_Present userId:User_ID nickName:model.u_nickname headPic:model.u_avatar msg:msg Level:model.level];
            [self.functionView.msgTableView bulletNewMsg:msgModel];
            
            for (NSDictionary *gitDict in array) {
                SPresentListModel *model = [[SPresentListModel alloc] initWithDict:gitDict];
                [_SpresentListArr addObject:model];
            }
            for (int i = 0; i < _SpresentListArr.count; i++) {
                UIButton *btn = _starPresentView.ButtonArray[i];
                SPresentListModel *prsentModel = _SpresentListArr[i];
                [btn setTitle:prsentModel.g_name forState:UIControlStateNormal];
            }
            [self SelectPresent:self.selectedBtn];
        }
    } failureBlock:^(NSError *error) {
        [self showTitle:@"连接服务器失败..."];
        [self hideHUD];
    } showHUD:NO];
}

#pragma mark -- 发送红包请求
//均分红包
- (void)sendEqualRedPaperRequestWithMoney:(NSString *)money Amount:(NSString *)amount {
    NSDictionary *dict = @{@"udid":User_ID,
                           @"token":TOKEN,
                           @"channel":_roomid,
                           @"money":money,
                           @"amount":amount};
    NSString *urlString = [TEST_URL stringByAppendingString:kRedFixed];
    [self showHUDInView:self.view title:@"红包发送中..."];
    [NetworkTools postReqeustWithParams:dict UrlString:urlString successBlock:^(id responseObject) {
        [self hideHUD];
        if ([KString(responseObject[@"code"]) isEqualToString:@"200"]) {
            LSMsgModel *msgModel = [[LSMsgModel alloc] init];
            msgModel.userName = [[LSUserInfoManager sharedManager] currentUserInfo].u_nickname;
            msgModel.userMsg  = responseObject[@"data"][@"message"];
            msgModel.userHeadImageUrl = [[LSUserInfoManager sharedManager] currentUserInfo].u_avatar;
            msgModel.msgType = TCMsgModelType_RedPaper;
            UserModel *model = [[LSUserInfoManager sharedManager] currentUserInfo];
            [_immsgHandler sendMessage:AVIMCMD_Star_Present userId:User_ID nickName:model.u_nickname headPic:model.u_avatar msg:msgModel.userMsg Level:model.level];
            [self.functionView.msgTableView bulletNewMsg:msgModel];
            [self closeRedPaperView];
        } else if ([KString(responseObject[@"code"]) isEqualToString:@"400"]) {
            [self showTitle:responseObject[@"data"][@"message"]];
        }
    } failureBlock:^(NSError *error) {
        [self hideHUD];
    } showHUD:NO];
}

//随机红包
- (void)sendEqualRandomPaperRequestWithMoney:(NSString *)money Amount:(NSString *)amount {
    NSDictionary *dict = @{@"udid":User_ID,
                           @"token":TOKEN,
                           @"channel":_roomid,
                           @"money":money,
                           @"amount":amount};
    NSString *urlString = [TEST_URL stringByAppendingString:kRedRandom];
    [self showHUDInView:self.view title:@"红包发送中..."];
    [NetworkTools postReqeustWithParams:dict UrlString:urlString successBlock:^(id responseObject) {
        [self hideHUD];
        if ([KString(responseObject[@"code"]) isEqualToString:@"200"]) {
            LSMsgModel *msgModel = [[LSMsgModel alloc] init];
            msgModel.userName = [[LSUserInfoManager sharedManager] currentUserInfo].u_nickname;
            msgModel.userMsg  = responseObject[@"data"][@"message"];
            msgModel.userHeadImageUrl = [[LSUserInfoManager sharedManager] currentUserInfo].u_avatar;
            msgModel.msgType = TCMsgModelType_RedPaper;
            UserModel *model = [[LSUserInfoManager sharedManager] currentUserInfo];
            [_immsgHandler sendMessage:AVIMCMD_Star_Present userId:User_ID nickName:model.u_nickname headPic:model.u_avatar msg:msgModel.userMsg Level:model.level];
            [self.functionView.msgTableView bulletNewMsg:msgModel];
            [self closeRedPaperView];
        } else if ([KString(responseObject[@"code"]) isEqualToString:@"400"]) {
            [self showTitle:responseObject[@"data"][@"message"]];
        }
  
    } failureBlock:^(NSError *error) {
        [self hideHUD];
        [self showTitle:@"连接服务器失败..."];
    } showHUD:NO];
 
}

//启动推流
- (void)startRtmpPushWithPushUrl:(NSString *)pushUrl {
    if (_txLivePush != nil) {
        [_txLivePush startPreview:self.videoView];
        if ([_txLivePush startPush:pushUrl]!=0) {
            //推流启动失败
            return;
        }
    }
}


#pragma mark -- LIving
- (void)setUpLive {
    //在 _config中您可以对推流的参数（如：美白，硬件加速，前后置摄像头等）做一些初始化操作，需要注意 _config不能为nil
    TXLivePushConfig* _config = [[TXLivePushConfig alloc] init];

    _config.frontCamera = YES;
    _config.enableAutoBitrate = NO;
    //由于iphone4s及以下机型前置摄像头不支持540p，故iphone4s及以下采用360p
    _config.videoResolution =  VIDEO_RESOLUTION_TYPE_540_960;
    _config.videoBitratePIN = 1000;
    _config.enableHWAcceleration = YES;
    
    //background push
    _config.pauseFps = 10;
    _config.pauseTime = 300;
    _config.homeOrientation = 1;
    //设置视频水印
    _config.watermark = [UIImage imageNamed:@"watermark.png"];
    _config.watermarkPos = (CGPoint){kSCREEN_WIDTH - 60, 130};
    
    //主播离开停顿界面
    _config.pauseImg = [UIImage imageNamed:@"LivingLeaveBackImg"];
    
    
    _txLivePush = [[TXLivePush alloc] initWithConfig: _config];
    _txLivePush.delegate = self;
    
    //输出log
//    [_txLivePush setLogLevel:LOGLEVEL_NULL];
    
}
- (void)setNav {
    [self.navigationController setNavigationBarHidden:YES animated:NO];
}

- (void)setUpUI{
    _SpresentListArr = [NSMutableArray arrayWithCapacity:1];
    
    UIView *videoView = [[UIView alloc] initWithFrame:self.view.bounds];
    videoView.backgroundColor = [UIColor darkGrayColor];
    self.videoView = videoView;
    [self.view addSubview:videoView];
    
    LivingfunctionView *functionView = [[NSBundle mainBundle] loadNibNamed:@"LivingfunctionView" owner:self options:nil].lastObject;
    functionView.delegate = self;
    functionView.frame = self.view.bounds;
    functionView.backgroundColor = [UIColor clearColor];
    self.functionView = functionView;
    [self.functionView.StarPhoto sd_setImageWithURL:[NSURL URLWithString:[LSUserInfoManager sharedManager].currentUserInfo.u_avatar] placeholderImage:kPlACE_ICON];
    self.functionView.starName.text = [LSUserInfoManager sharedManager].currentUserInfo.u_nickname;
    [self.view addSubview:functionView];
}

#pragma mark -- LivingfunctionViewDelegate 
- (void)functionClickWithSign:(NSString *)sign FunctionView:(LivingfunctionView *)functionView {
    if ([sign isEqualToString:@"1"]) {//发消息
       [self.functionView msgInputView];
    } else if ([sign isEqualToString:@"2"]){//送礼物
        [self sendPresent];
    } else if ([sign isEqualToString:@"3"]){//发红包
        [self SendRedPaper];
    } else if ([sign isEqualToString:@"4"]){//摄像头
        [_txLivePush switchCamera];
    } else if ([sign isEqualToString:@"5"]){//美颜
        [_txLivePush setBeautyFilterDepth:7 setWhiteningFilterDepth:5];
    } else {//关闭直播
        UIAlertController *alertVC= [UIAlertController alertControllerWithTitle:@"提示" message:@"您确认关闭直播吗?" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"关闭" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            [self CloseLiveRoom];
        }];
        [alertVC addAction:action];
        [alertVC addAction:action1];
        [self presentViewController:alertVC animated:YES completion:nil];
    }
}

#pragma mark -- 关闭直播(结束推流)
//关闭直播
- (void)CloseLiveRoom {
    //
    UserModel *model = [[LSUserInfoManager sharedManager] currentUserInfo];
    [_immsgHandler sendMessage:AVIMCMD_Star_ExitLive userId:model.udid nickName:model.u_nickname headPic:model.u_avatar msg:nil Level:model.level];
    if ([_txLivePush isPublishing]) {
        [self stopRtmpPush];
        [self showHUDInView:self.view title:@"关闭中..."];
        [[LSPushMgr alloc] changeLiveStatusWithRoomID:_roomid Chatroomid:_chatroomid Status:LSLiveStatus_Close Handle:^(NSError *error, NSString *msg) {
            [self hideHUD];
            if (error == nil) {//设置状态成功
                [self dismissViewControllerAnimated:NO completion:nil];
            }
        }];
    } else {
        [self dismissViewControllerAnimated:NO completion:nil];
    }
    
}
- (void)stopRtmpPush {
    if(_txLivePush != nil)
    {
        _txLivePush.delegate = nil;
        [_txLivePush stopPreview];
        [_txLivePush stopPush];
        _txLivePush.config.pauseImg = nil;
        _txLivePush = nil;
    }
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {

}

#pragma mark -- TXLviePushListener 
-(void) onPushEvent:(int)EvtID withParam:(NSDictionary*)param {
    NSDictionary* dict = param;
    
    dispatch_async(dispatch_get_main_queue(), ^{
        if (EvtID >= 0) {
            if (EvtID == PUSH_WARNING_HW_ACCELERATION_FAIL)
            {
                _txLivePush.config.enableHWAcceleration = false;
            }
            else if (EvtID == PUSH_EVT_PUSH_BEGIN)
            {
                //该事件表示推流成功，可以通知业务server将该流置为上线状态
                [[LSPushMgr alloc] changeLiveStatusWithRoomID:_roomid Chatroomid:_chatroomid Status:LSLiveStatus_Online Handle:^(NSError *error, NSString *code) {
                    if ([code intValue] == 200) {//设置状态成功
                        
                    } else {
                        [self showTitle:@"直播开启失败,请重新开启..."];
                        [self dismissViewControllerAnimated:NO completion:nil];
                    }
                }];
                 }
        } else {
            if (EvtID == PUSH_ERR_NET_DISCONNECT) {
                [self closeVCWithError:kErrorMsgNetDisconnected Alert:YES Result:YES];
            } else if (EvtID == PUSH_ERR_OPEN_CAMERA_FAIL) {
                [self closeVCWithError:kErrorMsgOpenCameraFailed Alert:YES Result:NO];
            } else if (EvtID == PUSH_ERR_OPEN_MIC_FAIL) {
                [self closeVCWithError:kErrorMsgOpenMicFailed Alert:YES Result:NO];
            } else {
                if (EvtID != PUSH_ERR_VIDEO_ENCODE_FAIL) {
                    [self closeVCWithError:(NSString*)[dict valueForKey:EVT_MSG] Alert:NO Result:NO];
                }
            }
        }
        
        long long time = [(NSNumber*)[dict valueForKey:EVT_TIME] longLongValue];
//        int mil = time % 1000;
//        NSDate* date = [NSDate dateWithTimeIntervalSince1970:time/1000];
        NSString* Msg = (NSString*)[dict valueForKey:EVT_MSG];
        NSLog(@"**%@",Msg);
    });

}

-(void) onNetStatus:(NSDictionary*) param {
    NSDictionary* dict = param;
    
    dispatch_async(dispatch_get_main_queue(), ^{
        int netspeed  = [(NSNumber*)[dict valueForKey:NET_STATUS_NET_SPEED] intValue];
        int vbitrate  = [(NSNumber*)[dict valueForKey:NET_STATUS_VIDEO_BITRATE] intValue];
        int abitrate  = [(NSNumber*)[dict valueForKey:NET_STATUS_AUDIO_BITRATE] intValue];
        int cachesize = [(NSNumber*)[dict valueForKey:NET_STATUS_CACHE_SIZE] intValue];
        int dropsize  = [(NSNumber*)[dict valueForKey:NET_STATUS_DROP_SIZE] intValue];
        int jitter    = [(NSNumber*)[dict valueForKey:NET_STATUS_NET_JITTER] intValue];
        int fps       = [(NSNumber*)[dict valueForKey:NET_STATUS_VIDEO_FPS] intValue];
        int width     = [(NSNumber*)[dict valueForKey:NET_STATUS_VIDEO_WIDTH] intValue];
        int height    = [(NSNumber*)[dict valueForKey:NET_STATUS_VIDEO_HEIGHT] intValue];
        float cpu_usage = [(NSNumber*)[dict valueForKey:NET_STATUS_CPU_USAGE] floatValue];
        int codecCacheSize = [(NSNumber*)[dict valueForKey:NET_STATUS_CODEC_CACHE] intValue];
        int nCodecDropCnt = [(NSNumber*)[dict valueForKey:NET_STATUS_CODEC_DROP_CNT] intValue];
        NSString *serverIP = [dict valueForKey:NET_STATUS_SERVER_IP];
        
        NSString* log = [NSString stringWithFormat:@"CPU:%.1f%%\tRES:%d*%d\tSPD:%dkb/s\nJITT:%d\tFPS:%d\tARA:%dkb/s\nQUE:%d|%d\tDRP:%d|%d\tVRA:%dkb/s\nSVR:%@\t",
                         cpu_usage*100,
                         width,
                         height,
                         netspeed,
                         jitter,
                         fps,
                         abitrate,
                         codecCacheSize,
                         cachesize,
                         nCodecDropCnt,
                         dropsize,
                         vbitrate,
                         serverIP];
        NSLog(@"%@",log);
        
    });

}

- (void)closeVCWithError:(NSString *)msg Alert:(BOOL)isAlert Result:(BOOL)isShowResult{
    if (isAlert) {
        if (isShowResult) {
            _closeErrRstAlert = [[UIAlertView alloc] initWithTitle:nil message:msg  delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [_closeErrRstAlert show];
        } else {
            _closeErrAlert = [[UIAlertView alloc] initWithTitle:nil message:msg  delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [_closeErrAlert show];
        }
    } else {
//        [self closeInternal];
    }
}


#pragma mark -- 送礼物
- (void)sendPresent {
    [self PresentListRequset];
    _starPresentView = [[NSBundle mainBundle] loadNibNamed:@"StarPresentView" owner:self options:nil].lastObject;
    _starPresentView.backgroundColor = [UIColor colorWithRed:0.00f green:0.00f blue:0.00f alpha:0.75];
    _starPresentView.frame = CGRectMake(0, kSCREEN_HEIGHT - kPresentHeight, kSCREEN_WIDTH, kPresentHeight);
    _starPresentView.delegate = self;
    [self.view addSubview:_starPresentView];
    
}

// 礼物发送
- (void)sendPresentClick:(UIButton *)sender {
    SPresentListModel *model = _SpresentListArr[self.selectedBtn.tag - 2000];
    [self sendPresentRequestWithPresentModel:model];
}
#pragma mark -- StarPresentViewDelegate
- (void)SelectPresent:(UIButton *)sender {
    SPresentListModel *model = _SpresentListArr[sender.tag - 2000];
    self.selectedBtn = sender;//记录当前选中按钮
    [sender setTitleColor:[UIColor mainColor] forState:UIControlStateNormal];
    for (UIButton *btn in _starPresentView.ButtonArray) {
        if (btn.tag - 2000 > _SpresentListArr.count - 1) {//防止礼物列表数小于按钮数 数组越界
            btn.hidden = YES;
        } else {
            btn.hidden = NO;
        }
        if (btn.tag !=sender.tag) {
            [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        }
    }
    _starPresentView.PresentType.text = model.g_name;
    _starPresentView.SponsorLab.text = model.g_sponsor;
    _starPresentView.quantity.text = KString(model.g_amount) ;

}
- (void)quatityClick:(UIButton *)sender {
    if (sender == _starPresentView.closeBtn) {//关闭礼物界面
        if (_starPresentView) {
            [_starPresentView removeFromSuperview];
        }
    } else if (sender == _starPresentView.SubBtn) {
        
    } else if (sender == _starPresentView.addBtn) {
        
    } else if (sender == _starPresentView.clearBtn) {
        
    }
}

#pragma mark -- 送礼物动画
- (void)giftAnimationWithMsgModel:(LSMsgModel *)msgModel {
    GiftModel *giftModel = [[GiftModel alloc] init];
    giftModel.headImage = [UIImage imageNamed:@"flower"];
    giftModel.name = msgModel.userName;
    giftModel.giftImage = [UIImage imageNamed:@"flower"];
    giftModel.giftName = msgModel.userName;
    giftModel.giftCount = 1;
    
    
    AnimOperationManager *manager = [AnimOperationManager sharedManager];
    manager.parentView = self.view;
    // 用用户唯一标识 msg.senderChatID 存礼物信息,model 传入礼物模型
    [manager animWithUserID:[NSString stringWithFormat:@"%@",msgModel.userId] model:giftModel finishedBlock:^(BOOL result) {
        
    }];

}
#pragma mark -- 发红包
- (void)SendRedPaper {
    if (!self.paperView) {
        SendRedPaperView *paperView = [[NSBundle mainBundle] loadNibNamed:@"SendRedPaperView" owner:self options:nil].lastObject;
        paperView.size = CGSizeMake(254, 325);
        paperView.center = self.view.center;
        self.paperView = paperView;
        self.paperView.delegate = self;
    }
    [self.functionView addSubview:self.paperView];
    self.paperView.moneyTextField.delegate = self;
    self.paperView.membersTextField.delegate = self;
    self.moneyTextField = self.paperView.moneyTextField;
    self.membersTextField = self.paperView.membersTextField;
    self.sendBtn = self.paperView.sendBtn;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark -- SendRedPaperDelegate
- (void)sendRedPapepr:(SendRedPaperView *)sendPaperView {
    NSString *money = sendPaperView.moneyTextField.text;
    NSString *amount = sendPaperView.membersTextField.text;
    
    if (![money isEqualToString:@""]&&![amount isEqualToString:@""]) {
        sendPaperView.sendBtn.enabled = YES;
    }
    switch (sendPaperView.paperType) {
        case RedPaperEqualType:
            [self sendEqualRedPaperRequestWithMoney:money Amount:amount];
            break;
        case RedPaperRandomType:
            [self sendEqualRandomPaperRequestWithMoney:money Amount:amount];
            break;
        default:
            break;
    }
}
//关闭红包界面
- (void)closeRedPaperView {
    [self closeRedPaper];
}

- (void)closeRedPaper {
    [self.paperView removeFromSuperview];
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    if (textField == self.moneyTextField||textField==self.membersTextField) {
       self.functionView.is_Msg = NO;
    } else {
        self.functionView.is_Msg = YES;
    }
    return YES;
}

#pragma mark -- 监测文本变化
- (void)textFieldChanged:(NSNotification *)notifica {
    if (self.moneyTextField.text.length>0&&self.membersTextField.text.length>0) {
        self.sendBtn.enabled = YES;
        self.sendBtn.backgroundColor = [UIColor colorWithHexString:@"FFCC00"];
    } else {
        self.sendBtn.enabled = NO;
        self.sendBtn.backgroundColor = [UIColor lightGrayColor];
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
